package com.pvdnc.xdynamic.loader.classloader;

import android.util.Log;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class SoUtils {
    private static final String TAG=SoUtils.class.getSimpleName();

    public static void mergePath(ClassLoader cl,String dir) throws Exception {
       mergePath(cl,new File(dir));
    }

    public static void mergePath(ClassLoader cl,File dir) throws Exception {
        if (!dir.isDirectory())
            throw new IllegalArgumentException("path:" + dir.getAbsolutePath() + " is not a dir");
        Object pathList = ClassLoaderUtils.getPathList(cl);
        //合并新path
        Field dirsField = pathList.getClass().getDeclaredField("nativeLibraryDirectories");
        List<File> dirs = (List<File>) dirsField.get(pathList);
        dirs.add(dir);
        dirsField.set(pathList,dirs);
        //更新pathList
        ClassLoaderUtils.setPathList(cl,pathList);
    }

    public static List<File> getNativeLibPathList(ClassLoader cl) {
        try {
            Object pathList = ClassLoaderUtils.getPathList(cl);
            Method[] methods = pathList.getClass().getDeclaredMethods();
            Method method = pathList.getClass().getDeclaredMethod("getNativeLibraryDirectories");
            List<File> libPathList = (ArrayList<File>) method.invoke(pathList);
            Log.d(TAG, "native lib path list:\n\t" + libPathList);
            return libPathList;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
